import { MissTargetError } from './../filter/error.filter';
import { BillCodeGenerator } from './../service/tool.service';
import {
  Body,
  Controller,
  Del,
  Get,
  Inject,
  Param,
  Post,
  Put,
} from '@midwayjs/core';
import {
  Material,
  MaterialDto4Modify,
  MaterialQueryCondition,
} from './../entity/material.entity';
import { Repository } from 'typeorm';
import { InjectEntityModel } from '@midwayjs/typeorm';
@Controller('/material')
export class MaterialController {
  @InjectEntityModel(Material)
  repo: Repository<Material>;
  @Inject()
  billCodeGenerator: BillCodeGenerator;
  @Post('/insert')
  async insert(@Body() material: Material) {
    material.materialCode = await this.billCodeGenerator.nextCode('MT');
    return await this.repo.save(material);
  }

  /* select * FROM Material m
  WHERE m.materialLable like '%器%' and m.materialType in ('machine','tool' )
  ORDER BY m.materialCode desc
  limit 0,2 */
  @Post('/query')
  async query(@Body() qc: MaterialQueryCondition) {
    console.log(qc);
    const { pageNum, pageSize, lableLike, materialTypes } = qc;
    const pageStart = (pageNum - 1) * pageSize;
    const builder = this.repo.createQueryBuilder('m');
    if (lableLike) {
      builder.andWhere('m.materialLable like :l', { l: '%' + lableLike + '%' });
    }
    if (materialTypes.length > 0) {
      builder.andWhere('m.materialType in ( :...types )', {
        types: materialTypes,
      });
    }
    builder
      .orderBy('m.materialCode ', 'DESC')
      .offset(pageStart)
      .limit(pageSize);
    const r = await builder.printSql().getManyAndCount();

    return {
      results: r[0],
      total: r[1],
    };
  }
  @Get('/find/:id')
  async findById(@Param('id') id: string) {
    const m = await this.repo.findOneBy({ materialCode: id });
    if (!m) {
      throw new MissTargetError('待查看的数据不存在');
    }
    return m;
  }
  @Del('/remove/:id')
  async removeById(@Param('id') id: string) {
    const m = await this.repo.findOneBy({ materialCode: id });
    if (!m) {
      throw new MissTargetError('待删除的数据不存在');
    }
    return await this.repo.remove(m);
  }
  @Put('/modify/:id')
  async modifyById(@Param('id') id: string, @Body() dto: MaterialDto4Modify) {
    const m = await this.repo.findOneBy({ materialCode: id });
    if (!m) {
      throw new MissTargetError('待修改的数据不存在');
    }
    // 修改 赋值
    // m.suggestPrice = dto.suggestPrice;
    // m.materialType = dto.materialType;
    Object.assign(m, dto);
    return await this.repo.save(m);
  }
  // 按照 类型 统计商品数量 方便柱状图
  // select m.materialType, count(1) from Material m
  // group by m.materialType;
  @Get('/echart/count')
  async count() {
    const r = await this.repo.query(
      'select m.materialType, count(1) as cnt from Material m group by m.materialType'
    );
    return r;
  }
}
